package com.norma.macaron.service.gateway.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhangchaofeng
 * @Date 18:08 2020/6/9 0009
 **/
@Service
public class AuthService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**从头取出jwt令牌*/
    public String getJwtFromHeader(ServerHttpRequest request){
        //取出头信息
        List<String> authorizations = request.getHeaders().get("Authorization");
        if(CollectionUtils.isEmpty(authorizations)){
            return null;
        }
        String authorization = authorizations.get(0);
        if(!authorization.startsWith("Bearer ")){
            return null;
        }
        //取到jwt令牌
        String jwt = authorization.substring(7);
        return jwt;
    }


    /**查询身份令牌*/
    public String getAccessToken(ServerHttpRequest request){
        List<String> access_token = request.getHeaders().get("uid");
        if(CollectionUtils.isEmpty(access_token)){
            return null;
        }

        return access_token.get(0);
    }

    /**查询令牌的有效期*/
     public long getExpire(String access_token){
        //key
         String key = "user_token:"+access_token;
         Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
         return expire;
     }
}
